<?php

namespace App\Models\Shop;

use App\Libraries\Tools\URL;
use App\Models\BaseModel;

class ShopComment extends BaseModel
{


    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'shop_id',
        'user_id',
        'comment'
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'updated_at'
    ];

    protected $dateFormat = 'U';


    /**
     * 关联用户
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user(){
        return $this->belongsTo('App\Models\User\User', 'user_id', 'user_id');
    }

    /**
     * 关联积分
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function points(){
        return $this->hasOne('App\Models\User\UserPoint', 'user_id', 'user_id');
    }

    /**
     * 根据shop_id获取商家评论
     * @param $shop_id
     * @param $page
     * @param $size
     * @return mixed
     */
    public function comments($shop_id, $page, $size){
        $data = [];
        $data['list'] = $this->select('shop_comments.*')
            ->rightJoin('users',function($join) {
                $join->on('shop_comments.user_id', '=', 'users.user_id')->where('users.status', 1);
            })
            ->withOnly('user', ['user_id', 'cover', 'nickname', 'vip_level'])
            ->with('points')
            ->where('shop_comments.shop_id', $shop_id)
            ->where('shop_comments.status', 1)
            ->orderBy('shop_comments.commented_at', 'desc')
            ->forPage($page, $size+1)
            ->get()
            ->toArray();
        $data['next_page'] = $page + 1;
        $data['page_size'] = $size;
        return $this->after($data);
    }

    /**
     * 添加评论
     * @param $id
     * @param $user_id
     * @param $content
     */
    public function add( $id, $user_id, $content, $score){
        $this->shop_id = $id;
        $this->user_id = $user_id;
        $this->comment = $content;
        $this->score = $score;
        $this->commented_at = time();
        $this->save();
    }

}
